package com.atguigu.day02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink01_Stream_WordCount_UnBounded {
    public static void main(String[] args) throws Exception {
        //1.创建流的执行环境
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //可以在本地查看webui
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        //将并行度设置为1  （企业生产中：并行度的设置通常和kafka的分区数一致）
        env.setParallelism(21);

        //全局都不串
//        env.disableOperatorChaining();

        //2.获取数据源(无界数据)
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999);

        //3.将读过来的一行数据按照空格切分切出每一个单词
        SingleOutputStreamOperator<String> wordDStream = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                //将一行数据按照单词切分
                String[] words = value.split(" ");
                //遍历出每一个单词
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        //4.将每一个单词组成Tuple2元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDStream = wordDStream.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        })
//                .disableChaining()//与前后都断开
                ;

        SingleOutputStreamOperator<Tuple2<String, Integer>> map = wordToOneDStream.map(r -> r).returns(Types.TUPLE(Types.STRING,Types.INT))
//                .startNewChain()//与前面断开
//                .slotSharingGroup("group 1") //开启新的共享组
                ;

        //5.将相同单词的数据聚和到一块
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = map.keyBy(value -> value.f0);

        //6.累加计算
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = keyedStream.sum(1);

        //7.打印到控制台
        sum.print();

        env.execute();
    }
}
